<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se tem permissao
validaPermissao(1);

// Descobre o id do funcionario em edicao
$employee_id = (isset($_GET['id'])? $_GET['id'] : $_SESSION[site_id]['id']);

// Verifica se tem permissao para acessar esta pagina:
// todos podem editar seus proprios dados, mas so admin pode editar
// os dados de todos.
if (nivelAutenticado() < 3 && !(edit_self_data && $employee_id == $_SESSION[site_id]['id']))
{
	forbidden();
}

// Verifica se houve envio do formulario.
if (isset($_POST['submit']))
{
	$driverexp = ($_POST['driverexp']? date("'Y-m-d'", strtotime($_POST['driverexp'])) : "NULL");

	// Trata figura
	if ($_FILES['picture'] && $_FILES['picture']['type'] != "")
	{
		// Validate the image type. Should be jpeg, jpg, gif or png.
		$allowed = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/png');
		if (! in_array($_FILES['picture']['type'], $allowed))
		{
			$errmsg = '<br>Please ensure the image is a JPEG, GIF or PNG.';
		}
		// Verifica o tamanho do arquivo
		else if (filesize($_FILES['picture']['tmp_name']) > 1024 * 500)
		{
			$errmsg = '<br>Please ensure to send a image smaller than 500kb.';
		}
		else
		{
            // atualiza bd
            query_bd("UPDATE employees SET has_picture=TRUE WHERE id={$_POST['id']} LIMIT 1");

            // Copia imagem para seu destino
            $filename = "portrails/{$_POST['id']}.jpg";
            copy($_FILES['picture']['tmp_name'], $filename);

            // Cria thumbnail
            // Get new dimensions
            list($width, $height) = getimagesize($filename);
            $crop_factor = (abs($width-48) < abs($height-62)? 
                            $width/48. : $height/62.);
            $crop_width  = 48. * $crop_factor;
            $crop_height = 62. * $crop_factor;

            // Resample
            $image_p = imagecreatetruecolor(48, 62);
            $image = imagecreatefromjpeg($filename);
            imagecopyresampled($image_p, $image, 0, 0, ($width-$crop_width)/2, 
                                                       ($height-$crop_height)/2, 
                                                       48, 62,
                                                       ($width+$crop_width)/2, 
                                                       ($height+$crop_height)/2);

            // Output
            imagejpeg($image_p, "portrails/{$_POST['id']}_thumb.jpg", 90);
		}
	}

	// Atualiza funcionario
	query_bd("UPDATE employees SET " .
	"socialsecurity=" . ($_POST['socialsecurity']? "'{$_POST['socialsecurity']}'" : "NULL") .
	", driverlicense=" . ($_POST['driverlicense']? "'{$_POST['driverlicense']}'" : "NULL") .
	", driverexp=" . ($_POST['driverexp']? "'" . date("Y-m-d", strtotime($_POST['driverexp'])) . "'" : "NULL") .
	(nivelAutenticado() >= 3? ", permission={$_POST['permission']}" : "") .
	(nivelAutenticado() >= 3? ", payrate=" . ($_POST['has_fixed_payrate'] && $_POST['payrate']? $_POST['payrate'] : "NULL") : "").
	", obs=" . ($_POST['obs']? "'" . mysql_real_escape_string($_POST['obs']) . "'" : "NULL") . " WHERE id={$_POST['id']} LIMIT 1");

	// descobre o numero do contato
	$contact_id = query_fetch("SELECT contact_id FROM employees WHERE id={$_POST['id']} LIMIT 1");

	// Atualiza contato
	query_bd("UPDATE contacts SET " .
	(nivelAutenticado() >= 3? "name=" . ($_POST['name']? "\"{$_POST['name']}\"," : "NULL,") : "") .
	"  number=" . ($_POST['number']? "{$_POST['number']}" : "NULL") .
	", street=" . ($_POST['street']? "\"{$_POST['street']}\"" : "NULL") .
	", complement=" . ($_POST['complement']? "\"{$_POST['complement']}\"" : "NULL") .
	", city=" . ($_POST['city']? "\"{$_POST['city']}\"" : "NULL") .
	", state=" . ($_POST['state']? "\"{$_POST['state']}\"" : "NULL") .
	", zipcode=" . ($_POST['zipcode']? "\"{$_POST['zipcode']}\"" : "NULL") .
	", phone=" . ($_POST['phone']? "\"{$_POST['phone']}\"" : "NULL") .
	", cellphone=" . ($_POST['cellphone']? "\"{$_POST['cellphone']}\"" : "NULL") .
	", email=" . ($_POST['email']? "\"{$_POST['email']}\"" : "NULL") .
	" WHERE id ={$contact_id['contact_id']} LIMIT 1");

	header( "Location: employee.php?id={$_POST['id']}&msg=Employee data update succesfully." . $errmsg );
	die();
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Edit Employee');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
pagina_head();

$employee = query_fetch("SELECT * FROM employees, contacts WHERE employees.id ='{$employee_id}' AND contacts.id = employees.contact_id LIMIT 1");

if (! $employee)
{
    response_404();
}

// Mostra opcao de cancelar edicao
echo "<ul id=opcoes>";
echo "<li class='negative'><a href='employee.php?id={$employee_id}'><img src='img/cancel.png' alt=''>Cancel Edit</a></li>";
echo "</ul><br>";

// Formulario de edicao do funcionario
echo "<form id=edit_employee class=big_form method='POST' enctype='multipart/form-data' action='employee_edit.php'>";
echo "<h1>Edit Employee's data</h1><br>";
echo "<input type=HIDDEN name=id value={$employee_id}>";
echo "<label for=name>Name:</label> <input type=TEXT id=name name=name value=\"{$employee['name']}\" size=40 maxlength=80 ",
	(nivelAutenticado() < 3? "readonly=TRUE" : ""), "><br>";

if (nivelAutenticado() >= 3)
	echo "<label for=picture>New picture:</label> <input type=FILE id=picture name=picture><br>";

echo "<hr><h2>Contact</h2><br>";
echo "<label for=number>Number:</label> <input type=TEXT id=number name=number value='{$employee['number']}' size=8 onChange='format_int(this)'>";
echo " <label for=street>Street:</label> <input type=TEXT id=street name=street value='{$employee['street']}' size=30 maxlength=50>";
echo " <label for=complement>Complement:</label> <input type=TEXT id=complement name=complement value='{$employee['complement']}' size=10 maxlength=30><br>";
echo "<label for=city>City:</label> <input type=TEXT id=city name=city value='{$employee['city']}' size=10 maxlength=30>";
echo " <label for=state>State:</label> <input type=TEXT id=state name=state value='{$employee['state']}' size=8 maxlength=10>";
echo " <label for=zipcode>Zipcode:</label> <input type=TEXT id=zipcode name=zipcode value='{$employee['zipcode']}' size=6 maxlength=10><br>";
echo "<label for=phone>Phone:</label> <input type=TEXT id=phone name=phone value='{$employee['phone']}' size=12 maxlength=20>";
echo " <label for=cellphone>Cellphone:</label> <input type=TEXT id=cellphone name=cellphone value='{$employee['cellphone']}' size=12 maxlength=20><br>";
echo "<label for=email>Email:</label> <input type=TEXT id=email name=email value='{$employee['email']}' size=20 maxlength=30>";

echo "<hr><h2>Work data</h2><br>";

if (nivelAutenticado() >= 3)
{
	echo "<label for=has_fixed_payrate>Has fixed payrate</label> ",
		"<input type=CHECKBOX name=has_fixed_payrate id=has_fixed_payrate ", ($employee['payrate']? "checked='CHECKED'" : ""), " value=1 ",
		"onChange='document.getElementById(\"payrate_show\").style.display = (document.getElementById(\"has_fixed_payrate\").checked? \"\" : \"none\" )'>", 	"<br>";
	echo "<div id=payrate_show ", ($employee['payrate']? "" : "style='display: none'"), ">";
	echo "<label for=payrate>Fixed payrate:</label> " .
		"$<input type=TEXT name=payrate id=payrate size=6 value='{$employee['payrate']}' onChange='format_money(this)'><br>";
	echo "</div>";
}

echo "<label for=socialsecurity>Social Security:</label> <input type=TEXT id=socialsecurity name=socialsecurity value='{$employee['socialsecurity']}' size=10 maxlength=20><br>";
echo "<label for=driverlicense>Driver license:</label> <input type=TEXT id=driverlicense name=driverlicense value='{$employee['driverlicense']}' size=10 maxlength=20>";
echo " <label for=driverexp>Driver license expiration date:</label> <input id=driverexp type=TEXT name=driverexp value='{$employee['driverexp']}' size=9>",
	"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'driverexp', 'chooserSpan1', 2008, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
	"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";;

if (nivelAutenticado() >= 3)
{
	echo "<hr><h2>Access Information</h2><br>";
	echo "<label for=permission>Access level:</label> <select id=permission name=permission>";
	echo "<option value=1 " . ($employee['permission']==1? "selected=SELECTED" : "") . ">Valet</option>";
	echo "<option value=2 " . ($employee['permission']==2? "selected=SELECTED" : "") . ">Manager</option>";
	echo "<option value=3 " . ($employee['permission']==3? "selected=SELECTED" : "") . ">Administrator</option>";
	if (nivelAutenticado() >= 4)
		echo "<option value=4 " . ($employee['permission']==4? "selected=TRUE" : "") . ">Super Administrator</option>";
	echo "</select>";
}

echo "<hr>";
echo "<label for=obs>Observations:</label><br><textarea id=obs name=obs cols=40 rows=5>";
echo $employee['obs'];
echo "</textarea>";
echo "<hr>";
echo "<input type=SUBMIT name=submit value='Submit'>";
echo "</form>";

// Finaliza pagina
pagina_fim();
?>
